package com.yuanxin.chooseimage;

import android.Manifest;
import android.app.Activity;
import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.google.gson.Gson;
import com.yalantis.ucrop.UCrop;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yuanxin.chooseimage.camera.VideoCameraActivity;
import com.yuanxin.chooseimage.customutil.ImageUtil;
import com.yuanxin.chooseimage.customutil.LocalUtil;
import com.yuanxin.chooseimage.customutil.VideoUtil;
import com.yuanxin.chooseimage.imagechoosemodule.MultiImageSelectorActivity;
import com.yuanxin.chooseimage.imagechoosemodule.bean.Image;
import com.yuanxin.chooseimage.imagechoosemodule.utils.FileUtils;
import com.yuanxin.chooseimage.photo.PreviewActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Mike on 2018/3/7.
 */

public class ImageChooseModule extends ReactContextBaseJavaModule implements ActivityEventListener {

    private static String TAG = ImageChooseModule.class.getSimpleName();
    private final int REQUEST_CAMERA_PERMISSION = 300;
    private final int REQUEST_IMAGE = 2;
    private final int CAMERA_VIDEO = 200;
    private final int CAMERA_PIC = 100;
    private final int CAMERA_PIC_CUT = 400;

    private String showChoosePath;
    private String resultType;
    private String tag;
    private int cutWidth;
    private int cutHeight;

    public ImageChooseModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "YuanXinImagePickerManager";
    }

    void showCameraActivity(final int total, final boolean isCut, String tag,
                            String resultType, final boolean isShowCamera, final int isPicVideo, String showChoosePath,
                            final int cameraType, final int maxSecond, final int cutWidth, final int cutHeight) {
        this.showChoosePath = showChoosePath;
        this.resultType = resultType;
        this.tag = tag;
        if (cameraType == 1) {
            AndPermission.with(getCurrentActivity())
                    .permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                    .onGranted(new Action() {
                        @Override
                        public void onAction(List<String> permissions) {
                            try {
                                chooseImage(total, isCut, isShowCamera, isPicVideo, cutWidth, cutHeight,maxSecond);
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    })
                    .onDenied(new Action() {
                        @Override
                        public void onAction(List<String> permissions) {
                            LocalUtil.PromiseReject("-100", "授权失败");
                            for (int i = 0; i < permissions.size(); i++) {
                                // Log.e(TAG, "拒绝了权限：" + permissions.get(i));
                            }
                        }
                    }).start();
        } else {
            AndPermission.with(getCurrentActivity())
                    .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                    .onGranted(new Action() {
                        @Override
                        public void onAction(List<String> permissions) {
                            try {
                                if (cameraType == 2) {
                                    showPhoto(isCut, cutWidth, cutHeight);
                                } else if (cameraType == 3) {
                                    showVideo(maxSecond);
                                }
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    })
                    .onDenied(new Action() {
                        @Override
                        public void onAction(List<String> permissions) {
                            LocalUtil.PromiseReject("-100", "授权失败");
                            for (int i = 0; i < permissions.size(); i++) {
                                // Log.e(TAG, "拒绝了权限：" + permissions.get(i));
                            }
                        }
                    }).start();
        }


    }

    String picFilePath;

    void showPhoto(boolean isCut, int cutWidth, int cutHeight) {
        this.cutHeight = cutHeight;
        this.cutWidth = cutWidth;
        Intent intent = new Intent();

        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);

        //保存照片到指定的路径
        File file = new File(getSDCacheDir("yuanxinpic") + "/" + System.currentTimeMillis() + ".png");
        picFilePath = String.valueOf(file);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(this.getCurrentActivity(), this.getCurrentActivity().getApplicationContext().getPackageName() + ".provider", file));
        }


        getCurrentActivity().startActivityForResult(intent, isCut ? CAMERA_PIC_CUT : CAMERA_PIC);
    }

    File videoFile;

    void showVideo(int maxSecond) {
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, maxSecond);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        // 保存录像到指定的路径
        videoFile = new File(getSDCacheDir("yuanxinvideo") + "/" + System.currentTimeMillis() + ".mp4");

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(videoFile));
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getCurrentActivity(), this.getCurrentActivity().getApplicationContext().getPackageName() + ".provider", videoFile));
        }

        getCurrentActivity().startActivityForResult(intent, CAMERA_VIDEO);
    }

    void chooseImage(int total, boolean isCut,
                     boolean isShowCamera, int isPicVideo,
                     int cutWidth, int cutHeight, int maxSecond) {
        int selectedMode = isCut ? MultiImageSelectorActivity.MODE_SINGLE : MultiImageSelectorActivity.MODE_MULTI;
        Intent intent = new Intent(this.getCurrentActivity(), MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, isShowCamera);
        // 显示图片，视频
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_PIC_VIDEO, isPicVideo);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, total);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, selectedMode);
        //是否需要剪切
        intent.putExtra(MultiImageSelectorActivity.EXTRA_IS_CUT, isCut);
        //剪切高度
        intent.putExtra(MultiImageSelectorActivity.EXTRA_CUT_WIDTH, cutWidth);
        //剪切宽度
        intent.putExtra(MultiImageSelectorActivity.EXTRA_CUT_HEIGHT, cutHeight);

        if(isPicVideo==1){
            //设置拍摄时长
            intent.putExtra(MultiImageSelectorActivity.EXTRA_MAX_SECOND, maxSecond);
        }

        this.getCurrentActivity().startActivityForResult(intent, isPicVideo == 0 ? REQUEST_IMAGE : CAMERA_VIDEO, null);
    }

    /*
        选择照片，视频
     */
    @ReactMethod
    public void launchImageLibrary(final ReadableMap map, final Promise promise) {
        getReactApplicationContext().addActivityEventListener(this);
        // Log.e(TAG, "map---" + map);
        LocalUtil.setPromise(promise);
        int total = 0;
        int maxSecond=6;
        boolean isCut = false;
        String tag = TAG;
        String type;
        boolean isShowCamera;
        int isPicVideo;
        if (map != null) {
            total = map.hasKey("maxCount") ? map.getInt("maxCount") : 0;
            maxSecond = map.hasKey("maxSecond") ? map.getInt("maxSecond") : 6;
            isShowCamera = map.hasKey("isShowCamera") ? map.getBoolean("isShowCamera") : false;
            isPicVideo = map.hasKey("IsChoose") ? map.getInt("IsChoose") : 0;
            type = map.hasKey("resultType") ? map.getString("resultType") : "object";
            showCameraActivity(total, isCut, tag, type, isShowCamera, isPicVideo, "launchImageLibrary", 1, maxSecond, 0, 0);
        } else {
            // Log.e(TAG, "Map是空的......");
        }

    }

    /*
        拍照录制
     */
    @ReactMethod
    public void getVideoThumbnailImage(final ReadableMap map, final Promise promise) {
        LocalUtil.setPromise(promise);
        Log.e(TAG, "getImageFromVideo Map是空的......");
        String videoPath=map.getString("videoPath");
        if(!TextUtils.isEmpty(videoPath)){
            Log.e(TAG, "getImageFromVideo Map是空的...videoPath..."+videoPath);
            String thumbnail = "";
            try {
                String path="";
                if (Build.VERSION.SDK_INT > 29) {
                    path = getCurrentActivity().getExternalFilesDir(null).getAbsolutePath() + "/" +  System.currentTimeMillis() + ".jpg";
                } else {
                    path = Environment.getExternalStorageDirectory().getPath() + "/" + System.currentTimeMillis() + ".jpg";
                }
                File file = new File(path);
                Bitmap bitmap = VideoUtil.getVideoThumbnail(videoPath);
                FileOutputStream out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();
                out.close();
                thumbnail = file.getAbsolutePath();

                WritableMap writableMap = Arguments.createMap();
                writableMap.putString("thumbnail", thumbnail);
                Log.e(TAG, "getImageFromVideo Map是空的... thumbnail..."+ thumbnail);
                LocalUtil.PromiseResolve(writableMap);

            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "getImageFromVideo Map是空的... IOException..."+ e);
                LocalUtil.PromiseReject(e);
            }
        }else{
            LocalUtil.PromiseReject(null);
        }
    }
    /*
        拍照录制
     */
    @ReactMethod
    public void launchCamera(final ReadableMap map, final Promise promise) {
        getReactApplicationContext().addActivityEventListener(this);
        LocalUtil.setPromise(promise);
        int IsCamera = map.hasKey("IsCamera") ? map.getInt("IsCamera") : 0;
        int maxSecond = map.hasKey("maxSecond") ? map.getInt("maxSecond") : 10;
        if (IsCamera == 0) //照片
        {
            boolean isEdite = map.hasKey("isEdite") ? map.getBoolean("isEdite") : false;
            int cutWidth = map.hasKey("cutWidth") ? map.getInt("cutWidth") : 150;
            int cutHeight = map.hasKey("cutHeight") ? map.getInt("cutHeight") : 150;
            showCameraActivity(0, isEdite, "", "", false, 0, "", 2, maxSecond, cutWidth, cutHeight);
        } else if (IsCamera == 1) //视频
            showCameraActivity(0, false, "", "", false, 0, "", 3, maxSecond, 0, 0);
    }

    public static String getSDCacheDir(String dirName) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String path = Environment.getExternalStorageDirectory() + File.separator + dirName;
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdir();
            }
            return dir.getAbsolutePath();
        } else {
            return "";
        }
    }

    @ReactMethod
    public void showImagePicker(final ReadableMap map, final Promise promise) {
        getReactApplicationContext().addActivityEventListener(this);
        // Log.e(TAG, "map---" + map);
        LocalUtil.setPromise(promise);
        int total = 0;
        boolean isCut = false;
        String tag = null;
        String type = null;
        int cutWidth = 0;
        int cutHeight = 0;
        boolean isShowCamera;
        if (map != null) {
            total = map.hasKey("maxCount") ? map.getInt("maxCount") : 0;
            isCut = map.hasKey("isEdite") ? map.getBoolean("isEdite") : false;
            cutWidth = map.hasKey("cutWidth") ? map.getInt("cutWidth") : 150;
            isShowCamera = map.hasKey("isShowCamera") ? map.getBoolean("isShowCamera") : false;
            cutHeight = map.hasKey("cutHeight") ? map.getInt("cutHeight") : 150;
            tag = map.hasKey("tagString") ? map.getString("tagString") : "";
            type = map.hasKey("resultType") ? map.getString("resultType") : "object";
            showCameraActivity(total, isCut, tag, type, isShowCamera, 0, "showImagePicker", 1, 0, cutWidth, cutHeight);
        } else {
            // Log.e(TAG, "Map是空的......");
        }
    }

    /**
     * 拍照预览
     */
    @ReactMethod
    public void showPhotoList(ReadableMap map, Promise promise) {
        getReactApplicationContext().addActivityEventListener(this);
        // Log.e(TAG, "showPhotoList-map---" + map);
        //默认值为0
        int showfirst = 0;
        //判断是否存在key  imageList
        ReadableArray imageList = null;
        if (map.hasKey("imageList")) {
            // Log.i(TAG, "imageList有数据");
            imageList = map.getArray("imageList");
        }
        //判断是否存在key  imgBase64List
        ReadableArray imgBase64List = null;
        if (map.hasKey("imgBase64List")) {
            // Log.i(TAG, "imgBase64List有数据");
            imgBase64List = map.getArray("imgBase64List");
        }
        //如果都不存在，直接返回
        if ((imageList == null || imageList.size() == 0) && (imgBase64List == null || imgBase64List.size() == 0)) {
            promise.reject(new Throwable("请输入正确的参数key:imageList|key:imgBase64List，或者数组为空"));
            return;
        }
        //判断是否存在key  showfirst
        if (map.hasKey("showfirst")) {
            showfirst = map.getInt("showfirst");
        }
        if (imageList != null && imageList.size() > 0 && showfirst >= imageList.size()) {
            showfirst = imageList.size() - 1;
        }
        if (imgBase64List != null && imgBase64List.size() > 0 && showfirst >= imgBase64List.size()) {
            showfirst = imgBase64List.size() - 1;
        }
        String[] imgPaths = new String[]{};
        if (imageList != null && imageList.size() > 0) {
            imgPaths = new String[imageList.size()];
            for (int i = 0; imageList.size() > i; i++) {
                String str = imageList.getString(i);
                imgPaths[i] = str;
            }
        }

        if (imgBase64List != null && imgBase64List.size() > 0) {
            PreviewActivity.imgBase64 = new String[imgBase64List.size()];
            for (int i = 0; imgBase64List.size() > i; i++) {
                String str = imgBase64List.getString(i);
                PreviewActivity.imgBase64[i] = str;
            }
        }

        Bundle bundle = new Bundle();
        bundle.putInt("showfirst", showfirst);
        if (imgPaths.length > 0)
            bundle.putStringArray("imgPaths", imgPaths);
        Intent intent = new Intent(getCurrentActivity(), PreviewActivity.class);
        intent.putExtras(bundle);
        getCurrentActivity().startActivity(intent);
    }

    public void sendEvent(ReactContext reactContext,
                          String eventName,
                          @Nullable WritableMap params) {
        reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
    }

    @ReactMethod
    public void captureVideo(final Promise promise) {
        LocalUtil.setPromise(promise);
        AndPermission.with(getCurrentActivity())
                .permission(Permission.CAMERA, Permission.RECORD_AUDIO, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                .onGranted(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        try {
                            Intent intent = new Intent(getCurrentActivity(), VideoCameraActivity.class);
                            getCurrentActivity().startActivity(intent);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                })
                .onDenied(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        LocalUtil.PromiseReject("-100", "授权失败");
                        for (int i = 0; i < permissions.size(); i++) {
                            // Log.e(TAG, "拒绝了权限：" + permissions.get(i));
                        }
                    }
                }).start();

    }


    class ResultData {
        private String tag;
        private List<Image> data;

        public ResultData(String tag, List<Image> data) {
            this.tag = tag;
            this.data = data;
        }
    }

    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        if (LocalUtil.isPromiseNull()) {
            Toast.makeText(getCurrentActivity(), "无法返回数据", Toast.LENGTH_SHORT).show();
            return;
        }
        if (getCurrentActivity().RESULT_OK != resultCode && !LocalUtil.isPromiseNull()) {
            LocalUtil.PromiseReject("error", "resultCode not is ok");
            return;
        }
        switch (requestCode) {
            case REQUEST_IMAGE:
                ArrayList<Image> mSelectPath = (ArrayList<Image>) data.getSerializableExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if (showChoosePath.equals("showImagePicker")) {
                    if (resultType.equals("") || resultType.equals("object")) {
                        WritableMap writableMap = Arguments.createMap();
                        writableMap.putString(TAG, tag);
                        WritableArray writableArray = Arguments.createArray();
                        for (Image item : mSelectPath) {
                            WritableMap map = Arguments.createMap();
                            map.putString("filePath", item.filePath);
                            map.putInt("height", item.height);
                            map.putInt("width", item.width);
                            map.putInt("type", item.type);
                            writableArray.pushMap(map);
                        }
                        writableMap.putArray("data", writableArray);
                        LocalUtil.PromiseResolve(writableMap);
                    } else {
                        LocalUtil.PromiseResolve(new Gson().toJson(new ResultData(tag, mSelectPath)));
                    }
                } else if (showChoosePath.equals("launchImageLibrary")) {
                    if (resultType.equals("") || resultType.equals("object")) {
                        WritableArray writableArray = Arguments.createArray();
                        for (Image item : mSelectPath) {
                            WritableMap map = Arguments.createMap();
                            map.putString("filePath", item.filePath);
                            map.putInt("height", item.height);
                            map.putInt("width", item.width);
                            map.putInt("type", item.type);
                            writableArray.pushMap(map);
                        }
                        LocalUtil.PromiseResolve(writableArray);
                    } else {
                        LocalUtil.PromiseResolve(new Gson().toJson(mSelectPath));
                    }
                }
                getReactApplicationContext().removeActivityEventListener(this);
                break;
            case CAMERA_VIDEO:
                if (data == null) {
                    LocalUtil.PromiseReject("error", "data is null");
                    return;
                }
                String uriPath = data.getStringExtra("filePath");//由launchImageLibrary选择视频后返回的
                if (uriPath == null || uriPath.equals("") && videoFile != null)
                    uriPath = videoFile.getAbsolutePath();//由launchCamera拍视频而来
                if (uriPath == null || uriPath.equals("")) {
                    LocalUtil.PromiseReject("ERROR", new String("没有获取到地址"));
                } else {
                    String thumbnail = "";
                    int duration = 0;
                    double fileSize=0;
                    try {
                        duration = VideoUtil.getVideoDuration(uriPath);
                        fileSize = FileSizeUtil.getFileOrFilesSize(uriPath,FileSizeUtil.SIZETYPE_KB);
                        String path="";
                        if (Build.VERSION.SDK_INT > 29) {
                            path = getCurrentActivity().getExternalFilesDir(null).getAbsolutePath() + "/" +  System.currentTimeMillis() + ".jpg";
                        } else {
                            path = Environment.getExternalStorageDirectory().getPath() + "/" + System.currentTimeMillis() + ".jpg";
                        }
                        File file = new File(path);
                        Bitmap bitmap = VideoUtil.getVideoThumbnail(uriPath);
                        FileOutputStream out = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                        out.flush();
                        out.close();
                        thumbnail = file.getAbsolutePath();

                        WritableMap writableMap = Arguments.createMap();
                        writableMap.putString("filePath", uriPath);
                        writableMap.putString("thumbnail", thumbnail);
                        writableMap.putInt("height", bitmap.getHeight());
                        writableMap.putInt("width", bitmap.getWidth());
                        writableMap.putInt("duration", duration);
                        writableMap.putDouble("fileSize", fileSize);//kb
                        LocalUtil.PromiseResolve(writableMap);

                    } catch (IOException e) {
                        e.printStackTrace();
                        LocalUtil.PromiseReject(e);
                    }
                }
                getReactApplicationContext().removeActivityEventListener(this);
                break;
            case CAMERA_PIC: {
                int rotationAngle = 0;
                try {
                    rotationAngle = ImageUtil.readPictureDegree(picFilePath);
                } catch (IOException e) {
                    e.printStackTrace();
                    LocalUtil.PromiseReject(e);
                }
                ImageUtil.compressBitmap(picFilePath);
                Bitmap bitmap = BitmapFactory.decodeFile(picFilePath);
                if (rotationAngle > 0) {
                    Bitmap newBitmap = ImageUtil.rotateBitmap(bitmap, rotationAngle);
                    bitmap.recycle();
                    try {
                        FileOutputStream fos = new FileOutputStream(picFilePath);
                        newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.flush();
                        fos.close();
                        bitmap = newBitmap;
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        LocalUtil.PromiseReject(ex);
                    }
                }

                WritableMap writableMap = Arguments.createMap();
                writableMap.putString("filePath", picFilePath);
                writableMap.putInt("type", 0);
                writableMap.putInt("height", bitmap.getHeight());
                writableMap.putInt("width", bitmap.getWidth());
                LocalUtil.PromiseResolve(writableMap);
            }
            getReactApplicationContext().removeActivityEventListener(this);
            break;
            case CAMERA_PIC_CUT: {
                Uri uri;
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                    uri = Uri.fromFile(new File(picFilePath));
                } else {
                    uri = FileProvider.getUriForFile(activity, activity.getApplicationContext().getPackageName() + ".provider", new File(picFilePath));
                }
                int color = Color.parseColor("#21282C");//这个颜色和图片列表一致
                UCrop.Options options = new UCrop.Options();
                options.setCropFrameStrokeWidth(2);//裁剪框线的所需宽度（像素）
                options.setCropGridStrokeWidth(2);//网格线的所需宽度（像素）
                options.setActiveWidgetColor(color);//横向滑轮颜色
                options.setToolbarColor(color);//导航栏颜色
                options.setLogoColor(color);//logo颜色 注意，这个logo一闪而过
                options.setRootViewBackgroundColor(color);// 背景色
                options.setToolbarWidgetColor(Color.WHITE);//导航栏按钮色
                options.setStatusBarColor(color);//状态栏颜色
                options.withAspectRatio(1, 1);//宽高比
                options.withMaxResultSize(cutWidth == 0 ? 300 : cutWidth * 2, cutHeight == 0 ? 300 : cutHeight * 2);
                File file = null;
                try {
                    file = FileUtils.createTmpFilePic(activity);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                UCrop.of(uri, Uri.fromFile(file))
                        .withOptions(options)
                        .start(activity);
            }
            break;
            case UCrop.REQUEST_CROP:
                Uri resultUri = UCrop.getOutput(data);
                if (resultUri != null && this != null) {
                    String filePath = uri2File(activity, resultUri).getAbsolutePath();

                    int rotationAngle = 0;
                    try {
                        rotationAngle = ImageUtil.readPictureDegree(filePath);
                    } catch (IOException e) {
                        e.printStackTrace();
                        LocalUtil.PromiseReject(e);
                    }
                    ImageUtil.compressBitmap(filePath);
                    Bitmap bitmap = BitmapFactory.decodeFile(filePath);
                    if (rotationAngle > 0) {
                        Bitmap newBitmap = ImageUtil.rotateBitmap(bitmap, rotationAngle);
                        bitmap.recycle();
                        try {
                            FileOutputStream fos = new FileOutputStream(filePath);
                            newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                            fos.flush();
                            fos.close();
                            bitmap = newBitmap;
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            LocalUtil.PromiseReject(ex);
                        }
                    }

                    WritableMap writableMap = Arguments.createMap();
                    writableMap.putString("filePath", filePath);
                    writableMap.putInt("type", 0);
                    writableMap.putInt("height", bitmap.getHeight());
                    writableMap.putInt("width", bitmap.getWidth());
                    LocalUtil.PromiseResolve(writableMap);
                }
                getReactApplicationContext().removeActivityEventListener(this);
                break;
        }
    }

    private File uri2File(Activity activity, Uri uri) {
        String img_path;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = null;
        if (Build.VERSION.SDK_INT < 11) {
            actualimagecursor = activity.managedQuery(uri, proj, null, null, null);
        } else {
            CursorLoader cursorLoader = new CursorLoader(activity, uri, null, null, null, null);
            actualimagecursor = cursorLoader.loadInBackground();
        }
        if (actualimagecursor == null) {
            img_path = uri.getPath();
        } else {
            int actual_image_column_index = actualimagecursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();
            img_path = actualimagecursor
                    .getString(actual_image_column_index);
        }
        File file = new File(img_path);
        return file;
    }

    @Override
    public void onNewIntent(Intent intent) {

    }
}
